package com.moses.tools;

import javassist.*;

import java.io.IOException;

public final class ClassByteTool {

    private final static ClassPool pool = ClassPool.getDefault();

    public static byte[] addHint(String className,String methodName) {
        byte[] bytes = new byte[0];
        CtClass ctClass = null;
        try {
            ctClass = pool.get(className);
            CtMethod ctMethod = ctClass.getDeclaredMethod(methodName);
            ctMethod.insertBefore("System.out.println(\"say hello start\");\n");
            ctMethod.insertAfter("System.out.println(\"say hello done\");\n");
            bytes = ctClass.toBytecode();
        } catch (NotFoundException | CannotCompileException | IOException e) {
            e.printStackTrace();
        } finally {
            if (ctClass != null) {
                ctClass.detach();
            }
        }
        return bytes;
    }

    public static byte[] addTimeHint(String className, String methodName, String methodBody) {
        byte[] bytes = new byte[0];
        StringBuilder body = new StringBuilder();

        CtClass ctClass = null;
        try {
            ctClass = pool.get(className);
            CtMethod ctMethod = ctClass.getDeclaredMethod(methodName);
            body.append("{\n");
            body.append("long start = System.currentTimeMillis();\n");
            body.append(methodBody);
            body.append("System.out.println(\"consume time \"+(System.currentTimeMillis()-start)+\" ms \");\n");
            body.append("}\n");
            ctMethod.setBody(body.toString());
            bytes = ctClass.toBytecode();
        } catch (NotFoundException | CannotCompileException | IOException e) {
            e.printStackTrace();
        } finally {
            if (ctClass != null) {
                ctClass.detach();
            }
        }
        return bytes;
    }



}
